package com.zhaojk.audio.domain;

import lombok.Data;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author zhaojk
 */
@Data
public class TrainingPage {
    private String targetWord;
    private TrainingType type;
    private boolean completed = false;

    public static void randomizePages(List<TrainingPage> pages) {
        // 1. 按targetWord分组，组内按order升序排序
        Map<String, List<TrainingPage>> groupedMap = new HashMap<>();
        for (TrainingPage page : pages) {
            groupedMap.computeIfAbsent(page.getTargetWord(), k -> new ArrayList<>()).add(page);
        }

        // 组内按order排序
        for (List<TrainingPage> group : groupedMap.values()) {
            group.sort(Comparator.comparingInt(p -> p.getType().getOrder()));
        }

        // 2. 准备迭代器集合
        List<Iterator<TrainingPage>> iterators = new ArrayList<>();
        List<String> keys = new ArrayList<>(groupedMap.keySet());

        // 3. 创建随机轮询迭代器
        for (String key : keys) {
            iterators.add(groupedMap.get(key).iterator());
        }

        // 4. 随机遍历所有元素
        List<TrainingPage> randomizedList = new ArrayList<>();
        Random random = ThreadLocalRandom.current();

        while (!iterators.isEmpty()) {
            // 随机选择一个非空迭代器
            int index = random.nextInt(iterators.size());
            Iterator<TrainingPage> iterator = iterators.get(index);

            // 取出下一个元素
            randomizedList.add(iterator.next());

            // 如果迭代器用完则移除
            if (!iterator.hasNext()) {
                iterators.remove(index);
            }
        }

        // 5. 替换原始列表
        pages.clear();
        pages.addAll(randomizedList);
    }
}
